extends CanvasLayer


@onready var player_label: Label = %PlayerLabel
@onready var flag_textures: Array[TextureRect] = [%HomeFlagTexture, %AwayFlagTexture]
@onready var score_label: Label = %ScoreLabel
@onready var time_label: Label = %TimeLabel
@onready var goal_scorer_label: Label = %GoalScorerLabel
@onready var score_info_label: Label = %ScoreInfoLabel
@onready var animation_player: AnimationPlayer = %AnimationPlayer

var last_ball_carrier: String = ""

func _ready() -> void:
	update_score()
	update_flags()
	update_clock()
	player_label.text = ""
	GameEvent.ball_possessed_request.connect(on_ball_possessed.bind())
	GameEvent.ball_released_request.connect(on_ball_released.bind())
	GameEvent.team_reset_request.connect(on_team_reset.bind())
	GameEvent.score_changed_request.connect(on_score_changed.bind())
	GameEvent.game_over_request.connect(on_game_over.bind())
	
func _process(_delta: float) -> void:
	update_clock()
	
func update_score() -> void:
	score_label.text = ScoreHelper.get_score_text(GameManager.current_match)
	
func update_flags() -> void:
	var countries = [GameManager.current_match.country_home, GameManager.current_match.country_away]
	for i in flag_textures.size():
		flag_textures[i].texture = FlagHelper.get_texture(countries[i])
		
func update_clock() -> void:
	if GameManager.time_left < 0:
		time_label.modulate = Color.YELLOW
	time_label.text = TimeHelper.get_time_text(GameManager.time_left)
	
func on_ball_possessed(player_name: String) -> void:
	player_label.text = player_name
	last_ball_carrier = player_name
	
func on_ball_released() -> void:
	player_label.text = ""

func on_team_reset() -> void:
	if GameManager.current_match.has_someone_scored():
		animation_player.play("goal_hide")
	
func on_score_changed() -> void:
	if not GameManager.is_time_up():
		goal_scorer_label.text = "%s SCORED!" % last_ball_carrier
		score_info_label.text = ScoreHelper.get_current_score_info(GameManager.current_match)
		animation_player.play("goal_appear")
	update_score()
	
func on_game_over(_country_winner:String) -> void:
	score_info_label.text = ScoreHelper.get_final_score_info(GameManager.current_match)
	animation_player.play("game_over")
